package com.zjxh.zjxh.mob.service.impl;

import com.zjxh.zjxh.common.Result;
import com.zjxh.zjxh.common.constant.CMEnum;
import com.zjxh.zjxh.common.constant.Constant;
import com.zjxh.zjxh.common.exception.CommonException;
import com.zjxh.zjxh.common.util.SnowflakeIdWorker;
import com.zjxh.zjxh.config.MinioConfig;
import com.zjxh.zjxh.mob.mapper.FileCommonMapper;
import com.zjxh.zjxh.mob.service.FileService;
import com.zjxh.zjxh.mob.vo.req.FileUploadReq;
import com.zjxh.zjxh.mob.vo.resp.FileUploadResp;
import com.zjxh.zjxh.pojo.FileCommon;
import java.time.LocalDateTime;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author: oyp
 * @date: 2024/5/29 on 15:00
 * @desc:
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class FileServiceImpl implements FileService {

  private final FileCommonMapper fileCommonMapper;
  private final MinioConfig minioConfig;

  public FileServiceImpl(FileCommonMapper fileCommonMapper, MinioConfig minioConfig) {
    this.fileCommonMapper = fileCommonMapper;
    this.minioConfig = minioConfig;
  }

  /**
   * 上传图片
   *
   * @param request
   * @param req
   * @return
   */
  @Override
  public Result<FileUploadResp> fileUpload(HttpServletRequest request, FileUploadReq req) {
    Long id = SnowflakeIdWorker.generateId();
    // 获取文件后缀
    String filename = req.getImage().getOriginalFilename();
    String path = null;
    if (filename != null) {
      String suffix = filename.substring(filename.lastIndexOf("."));
      if (!".jpg".equals(suffix)
          & !".png".equals(suffix)
          & !".PNG".equals(suffix)
          & !".JPG".equals(suffix)
          & !".jpeg".equals(suffix)
          & !".JPEG".equals(suffix)) {
        throw new CommonException(CMEnum.ERROR_ARGS_VERIFY, "仅支持图片和音频、视屏文件上传");
      }
      try {
        path = this.minioConfig.putObject(req.getImage());
      } catch (Exception e) {
        e.printStackTrace();
      }
      int insert =
          fileCommonMapper.insert(
              new FileCommon()
                  .setId(id)
                  .setPath(path)
                  .setType(req.getFileEnum())
                  .setCreateAt(LocalDateTime.now()));
      if (insert != Constant.INT_ONE) {
        throw new CommonException(CMEnum.ERROR_INSERT);
      }
      return Result.success(new FileUploadResp().setId(id).setUrl(path));
    } else {
      throw new CommonException(CMEnum.ERROR);
    }
  }
}
